package com.mogician.feihualing.feihualing;

import android.content.Context;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
{

    String key;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText input = (EditText)findViewById(R.id.key_input);
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        Context context = this;
        input.addTextChangedListener(new TextWatcher()
        {
            boolean completed = true;
            Thread thread;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {

            }

            @Override
            public void afterTextChanged(Editable s)
            {
                if(!completed)
                {
                    thread.interrupt();
                }
                else
                {
                    thread = new Thread()
                    {
                        @Override
                        public void run()
                        {
                            completed = false;
                            key = input.getText().toString();
                            ArrayList<Poem> poemList = PoemUtil.parseAndFilter(
                                    context, "poems", key);
                            if(!poemList.isEmpty())
                            {
                                PoemAdapter adapter = new PoemAdapter(poemList, key);
                                recyclerView.setAdapter(adapter);
                            }
                            else
                            {
                                Toast.makeText(getApplicationContext(),
                                        "未搜索到包含关键词的结果", Toast.LENGTH_SHORT)
                                        .show();
                            }
                            completed = true;
                        }
                    };
                    thread.run();
                }
            }
        });
    }

}
